package com.pioneer.gui.invoice.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

public class ConnectionServer
{	
    private final String DRIVER="driver";
    private final String URL="url";
    private final String USER="user";
    private final String PASSWORD="password"; 
    private Properties _prop;
    private static ConnectionServer _connServer=null;
    private Connection _conn;

    public static ConnectionServer getSingleton()
    {
    	if (_connServer==null)
    	{
    		_connServer=new ConnectionServer();
    	}    	
    	return _connServer;    	
    }
    
    private ConnectionServer()
    {
    	_prop=null;
    	_conn=null;
    }
    
    public void initialize(String propFileName)    
    {
        this._prop=new Properties();
        try
        {
            this._prop.load(new FileInputStream(new File(propFileName)));
            this._conn=this.getConnection();
        }
        catch (SQLException e)
        {
        	System.out.println(e.toString());
        }
        catch (IOException e)
        {
            System.out.println(e.toString());
        }
    }    
    
    public Connection getConnection()
    throws NotYetInitializedException
    {    	
    	try
        {
        	if (this._prop==null) throw new NotYetInitializedException();
        	if ((this._conn!=null) && (!this._conn.isClosed()) )return this._conn;        
            Class.forName(_prop.getProperty(DRIVER));
            this._conn=DriverManager.getConnection(_prop.getProperty(URL),_prop.getProperty(USER),_prop.getProperty(PASSWORD));
        }
        catch (ClassNotFoundException e)
        {        	
            System.out.println(e.toString());
            //throw new NotYetInitializedException();
        }
        catch (SQLException e)
        {
            System.out.println(e.toString());
            //throw new NotYetInitializedException();
        }
        return _conn;
    }
    
}